package com.hxd.Login.LoginController;

import com.alibaba.fastjson.JSONArray;
import com.hxd.Login.LoginService.loginService;
import com.hxd.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class loginController {
    @Autowired
    loginService loginService;

    //初始登录：http://localhost:8080
    @GetMapping({"/", "login"})
    public String index(HttpSession session) {
        session.invalidate();
        return "Login/login";
    }

    //忘记密码跳转
    @GetMapping("home")
    public String home() {
        return "Login/home";
    }

    //登录验证信息
    @PostMapping("verification")
    @ResponseBody
    public String verification(User user, String verify, HttpSession session) {
        String code = (String) session.getAttribute("code");
        if (code != null && code.equals(verify)) {
            Boolean bool = loginService.verify(user,session);
            if (bool) {
                session.removeAttribute("code");
                return "OK";
            }
            return "FAIL";
        }
        return "CODE";
    }

    //生成登录验证码
    @GetMapping("getImage")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        loginService.getImage(session,response);
    }

    //根据用户名查询出来信息自动填充姓名邮箱
    @GetMapping("verification")
    @ResponseBody
    public String verification(User user) {
        User user1 = loginService.verification(user);
        if (user1 != null) {
            String data = JSONArray.toJSONString(user1);
            return data;
        }
        return "Fail";
    }

    //获取邮件验证码
    @PostMapping("verifeCode")
    @ResponseBody
    public String verifeCode(User user, String verify, HttpSession session) throws MessagingException {
        Integer num = loginService.verifeCode(user);
        if (num > 0) {
            session.setAttribute(user.getUser_id().toString() + "code", num.toString());
            System.out.println("-------邮箱验证码-----" + num.toString());
            return "OK";
        }
        return "Fail";
    }

    //发送验证码,修改密码
    @PostMapping("obtain")
    @ResponseBody
    public String obtain(User user, String verify, HttpSession session) {
        String userCode = (String) session.getAttribute(user.getUser_id().toString() + "code");
        if (userCode != null && !"".equals(userCode) && userCode.equals(verify)) {
            loginService.modifyUserPassword(user);
            session.removeAttribute(user.getUser_id().toString() + "code");
            return "OK";
        }
        return "Fail";
    }


}
